package events.listenerWrappers;

import java.lang.ref.WeakReference;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import zerdlib.events.ListenerWrapper;
import zerdlib.events.WeakListenerWrapper;

public class WeakListDataListenerWrapper implements ListDataListener, WeakListenerWrapper<ListDataListener> {
	private final WeakReference<ListDataListener> wrapped;
	private final ListModel<?> listened;
	
	private WeakListDataListenerWrapper(ListDataListener wrapped, ListModel<?> listened) {
		super();
		this.wrapped = new WeakReference<ListDataListener>(wrapped);
		this.listened = listened;
	}

	@Override
	public void intervalAdded(ListDataEvent e) {
		if(wrapped == null) {
			listened.removeListDataListener(this);
		} else {
			wrapped.get().intervalAdded(e);
		}
	}

	@Override
	public void intervalRemoved(ListDataEvent e) {
		if(wrapped == null) {
			listened.removeListDataListener(this);
		} else {
			wrapped.get().intervalRemoved(e);
		}
	}

	@Override
	public void contentsChanged(ListDataEvent e) {
		if(wrapped == null) {
			listened.removeListDataListener(this);
		} else {
			wrapped.get().contentsChanged(e);
		}
	}
	
	public static void addWeakListDataListener(ListModel<?> listened, ListDataListener listener) {
		listened.addListDataListener(new WeakListDataListenerWrapper(listener, listened));
	}

	@SuppressWarnings("unchecked")
	@Override
	public ListDataListener getWrappedListener() {
		if(wrapped.get() instanceof ListenerWrapper<?>) {
			return ((ListenerWrapper<ListDataListener>) wrapped.get()).getWrappedListener();
		} else {
			return wrapped.get();
		}
	}

}
